package com.mz3co.sysadmin.security;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

//import com.mz3co.sysadmin.model.SysCustomer;
//import com.mz3co.sysadmin.model.SysEmployee;
import com.mz3co.sysadmin.model.SysUsers;
import com.mz3co.sysadmin.model.SysUsersRoles;
import com.mz3co.sysadmin.model.ex.SysUsersEx;
import com.mz3co.sysadmin.security.utils.AuthencationResult;
//import com.mz3co.sysadmin.security.utils.LoginingCustomer;
//import com.mz3co.sysadmin.service.SysCustomerService;
//import com.mz3co.sysadmin.service.SysEmployeeService;
import com.mz3co.sysadmin.service.SysRolesResourcesService;
import com.mz3co.sysadmin.service.SysUsersRolesService;
import com.mz3co.sysadmin.service.utils.DataAuthorityRegister;
import com.mz3co.sysadmin.service.utils.SysConst;

public class MySimpleUrlAuthenticationSuccessHandler extends
		SimpleUrlAuthenticationSuccessHandler {

	@Autowired
	private SysRolesResourcesService rolesResourcesService;

	@Autowired
	private SysUsersRolesService usersRolesService;
	
/*
	@Autowired
	private SysEmployeeService employeeService;


	@Autowired
	private SysCustomerService customerService;
*/

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		this.dispatcher(request, response);
	}

	/**
	 * 根据登陆的用户类型进行跳转
	 * 
	 * @param response
	 * @param sysUser
	 * @throws IOException
	 * @throws ServletException
	 */
	private void dispatcher(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		AuthencationResult authResult = new AuthencationResult();

		this.setAuthencationResult(request, authResult);

		out.print(JSONObject.fromObject(authResult));
		out.flush();

		// 选择的登陆系统与角色不匹配，跳转到Error页面，例如客户登陆账号，试图登陆到管理子系统
		request.getRequestDispatcher("index.jsp").forward(request, response);
		out.close();
	}

	private void setAuthencationResult(HttpServletRequest request,
			AuthencationResult authResult) {

		SysUsers user = (SysUsers) request.getAttribute("sysUser");

		authResult.setUser(user);
		authResult.setLoginingAccount((String) request
				.getAttribute("loginingAccount"));
		authResult.setStatus(true);
		authResult.setMsg("登陆验证成功！");
		
		
		HttpSession session = request.getSession();
		
/*		// 嘉宾登陆
		if ("嘉宾".equals(user.getType())) {
			
			LoginingCustomer loginingCustomer = new LoginingCustomer();

			SysCustomer customer = customerService.getCustomer(user
					.getUserDetailId());

			authResult.setCustomer(customerService.getCustomer(user
					.getUserDetailId()));

			this.setSessionForCustomer(session, user, customer);
		}

		// 嘉宾登陆
		if ("客商".equals(user.getType())) {

			LoginingCustomer loginingCustomer = new LoginingCustomer();

			SysCustomer customer = customerService.getCustomer(user
					.getUserDetailId());

			try {
				BeanUtils.copyProperties(loginingCustomer, customer);

			} catch (IllegalAccessException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			authResult.setCustomer(loginingCustomer);

			this.setSessionForCustomer(session, user, customer);

		}
		// 嘉宾登陆
		if ("员工".equals(user.getType())) {

			SysEmployee employee = employeeService.getEmployeeById(user
					.getUserDetailId());

			authResult.setEmployee(employee);

			// todo 设置主菜单
			JSONObject menuJSON = SysConst.RESOURCESTREE
					.bulidMenuResourceTree(rolesResourcesService
							.getResourcesIdList(user.getId()));

			authResult.setMenuJSON(menuJSON);

			this.setSessionForEmployee(session, user, employee);

		}
		*/
	

	}

/*	public void setSessionForCustomer(HttpSession session,SysUsers user,SysCustomer customer) {

		SysUsersEx userEx = new SysUsersEx();

		try {
			
			BeanUtils.copyProperties(userEx, user);
			
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//说明当前登陆的是客户，创建的所有记录的数据访问组为-1
		userEx.setCounterMan(-1);
		userEx.setAccessGroup("-1");
		
		session.setAttribute("loginingUser", userEx);
		
		
	}

	
	public void setSessionForEmployee(HttpSession session,SysUsers user,SysEmployee employee ) {

		SysUsersEx userEx = new SysUsersEx();

		try {
			
			BeanUtils.copyProperties(userEx, user);
			
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//说明当前登陆的是客户，创建的所有记录的数据访问组为 该员工所在
		userEx.setCounterMan(employee.getEmployeeId());
		userEx.setAccessGroup(employee.getEmployeeDepartment() ==null?"-1":
			employee.getEmployeeDepartment().toString());
		
		session.setAttribute("loginingUser", userEx);
		
	}*/

	// ******************************************************************以下参考可以删除

	/**
	 * 当登陆后台管理系统，根据授权成功信息设置服务器端的session及客户端的cookie信息
	 * 
	 * @param response
	 * @param user
	 * @param sysUser
	 */
	private void setAuthenticationInfoFor_ADMIN(HttpServletRequest request,
			HttpServletResponse response, SysUsersEx httpUser) {

		HttpSession session = request.getSession();

//		this.setSessionInfoFor_ADMIN(session, httpUser);

		try {
			Cookie userNameCookie = new Cookie("userName", URLEncoder.encode(
					httpUser.getUsername(), "UTF-8"));

			Cookie roleResourceIds = new Cookie("roleResourceIds",
					rolesResourcesService.getResourcesIds(httpUser.getId().intValue()));// todo
																				// 添加资源类型：type
																				// "前端，后端"

			// todo 设置主菜单
			JSONObject menusJO = SysConst.RESOURCESTREE
					.bulidMenuResourceTree(rolesResourcesService
							.getResourcesIdList(httpUser.getId().intValue()));

			Cookie menus = new Cookie("menus", URLEncoder.encode(
					menusJO.toString(), "UTF-8"));

			userNameCookie.setPath("/cnscecms-admin");
			roleResourceIds.setPath("/cnscecms-admin");

			response.addCookie(userNameCookie);
			response.addCookie(roleResourceIds);
			response.addCookie(menus);

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*private void setSessionInfoFor_ADMIN(HttpSession session,
			SysUsersEx httpUser) {

		// 将登陆的用户信息放到session中
		session.setAttribute("user", httpUser);

		SysEmployee employee = employeeService.getEmployeeById(httpUser
				.getUserDetailId());

		if (employee == null || employee.getEmployeeDepartment() == null)
			;
		else

			httpUser.setAccessGroup(employee.getEmployeeDepartment().toString());

		// session.setAttribute("employee",);

		// 添加数据授权登记
		DataAuthorityRegister dataAuthorityRegister = new DataAuthorityRegister();

		session.setAttribute("dataAuthorityRegister", dataAuthorityRegister);

		// session.setAttribute("employee", employee);

		// 添加角色集合
		List<Integer> roleList = new ArrayList<Integer>();

		for (SysUsersRoles ur : usersRolesService
				.getUserRoles(httpUser.getId())) {
			roleList.add(ur.getRid());
		}

		session.setAttribute("roleList", roleList);

	}*/

	/**
	 * 当登陆前端报名系统，根据授权成功信息设置服务器端的session及客户端的cookie信息
	 * 
	 * @param response
	 * @param user
	 * @param sysUser
	 */
	private void setAuthenticationInfoFor_CUSTOMER(HttpServletRequest request,
			HttpServletResponse response, SysUsers user) {

		// *************************参考代码
		// HttpSession session = request.getSession();

		// this.setSessionInfoFor_PORTALSYSTEM(session, user);

		// try {

		// Cookie userNameCookie = new Cookie("userName", URLEncoder.encode(
		// user.getUsername(), "UTF-8"));
		//
		// //前端根据roleResourceIds 设置菜单
		// Cookie roleResourceIds = new Cookie("roleResourceIds",
		// rolesResourcesService.getResourcesIds(user.getId()));//添加资源类型：
		// type="前端"

		// todo 设置主菜单
		// JSONObject menusJO =
		// SysConst.RESOURCESTREE.bulidMenuResourceTree(rolesResourcesService.getResourcesIdList(httpUser.getId()));
		//
		// Cookie menus = new Cookie("menus",URLEncoder.encode(
		// menusJO.toString(), "UTF-8"));

		// userNameCookie.setPath("/cnscecms-portalSystem");
		// roleResourceIds.setPath("/cnscecms-portalSystem");
		//
		// response.addCookie(userNameCookie);
		// response.addCookie(roleResourceIds);
		// response.addCookie(menus);

		// } catch (UnsupportedEncodingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	// 将登陆的信息放到session中
	/*private void setSessionInfoFor_PORTALSYSTEM(HttpSession session,
			SysUsersEx httpUser) {

		session.setAttribute("user", httpUser);

		SysCustomer customer = customerService.getCustomer(httpUser
				.getUserDetailId());

		if (customer == null) {
			httpUser.setLoginStatus("The Customer is unexist!");

			return;
		}

		// accessgroup = -1 说明当前登陆的用户为 客户
		httpUser.setAccessGroup("-1");

	}*/

}
